package com.zbkj.client.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.client.discovery.Contacts;
import com.zbkj.client.service.ContactsService;
import com.zbkj.client.config.ClientTokenComponent;
import com.zbkj.common.model.client.workbench.VideoTemplateFinal;
import com.zbkj.common.response.ClientLoginResponse;
import com.zbkj.common.response.client.ContactsListResponse;
import com.zbkj.common.utils.OssUtil;
import com.zbkj.service.dao.client.ContactsDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
public class ContactsServiceImpl implements ContactsService {

    private static final Logger log = LoggerFactory.getLogger(ContactsServiceImpl.class);

    @Autowired
    private ContactsService serviceContactsService;
    
    @Autowired
    private ClientTokenComponent clientTokenComponent;

    @Autowired
    private ContactsDao contactsDao;

    @Override
    public List<Contacts> getContactsListByUserId(Integer parentId, Integer userId) {
        
        // 构建查询条件
        QueryWrapper<Contacts> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("is_del", 0)
                   .eq("parent_id", parentId)
                   .orderByAsc("create_time");
        
        // 查询通讯录列表
        return contactsDao.selectList(queryWrapper);
    }

    @Override
    public List<ContactsListResponse> getContactsListWithHeadImg(Integer parentId, Integer userId) {
        // 记录SQL查询日志
        log.info("执行selectContactsListWithHeadImg查询，参数：parentId={}, userId={}", parentId, userId);
        log.info("SQL: SELECT c.id, c.name, c.is_folder as isFolder, c.is_del as isDel, c.user_id as userId, c.mer_id as merId, c.parent_id as parentId, c.complete_folder as completeFolder, c.link_id as linkId, c.type, c.create_time as createTime, c.update_time as updateTime, CASE WHEN c.type = 'agent' THEN a.head_img WHEN c.type = 'group' THEN g.head_img ELSE NULL END as headImg FROM eb_client_contacts c LEFT JOIN eb_client_agent a ON c.type = 'agent' AND c.link_id = a.agent_id AND a.is_del = 0 LEFT JOIN eb_client_group g ON c.type = 'group' AND c.link_id = g.group_id AND g.is_del = 0 WHERE c.user_id = {} AND c.is_del = 0 AND c.parent_id = {} ORDER BY c.create_time ASC", userId, parentId);
        
        // 使用自定义查询方法，包含左连接查询头像信息
        List<ContactsListResponse> result = contactsDao.selectContactsListWithHeadImg(parentId, userId);
        
        log.info("selectContactsListWithHeadImg查询完成，返回结果数量：{}", result != null ? result.size() : 0);
        
        return result;
    }

    //将代理添加到通讯录
    @Override
    public boolean addContact(Integer parentId, String agentId, Integer userId, Integer merId, String type, String name) {
        try {
            // 创建新的Contacts对象
            Contacts contacts = new Contacts();
            
            // 设置基本信息
            contacts.setUserId(userId);
            contacts.setMerId(merId);
            contacts.setLinkId(agentId);
            contacts.setIsFolder(0); // is_folder = 0
            contacts.setIsDel(0); // is_del = 0
            contacts.setType(type); // 类型
            contacts.setName(name); // 类型
            contacts.setCreateTime(new Date());
            contacts.setUpdateTime(new Date());
            
            // 处理parentId和complete_folder
            if (parentId != null && parentId > 0) {
                // 如果parentId不为空，获取父级记录的complete_folder
                Contacts parentContact = contactsDao.selectById(parentId);
                if (parentContact != null) {
                    contacts.setParentId(parentId);
                    // 拼接complete_folder：父级的complete_folder + parent_id/
                    String parentCompleteFolder = parentContact.getCompleteFolder();
                    if (parentCompleteFolder != null && !parentCompleteFolder.isEmpty()) {
                        //拼接 父级的complete_folder + parent_id + /
                        contacts.setCompleteFolder(parentCompleteFolder + parentId + "/");
                    } else {
                        //不会走到这里
                        contacts.setCompleteFolder(parentId + "/");
                    }
                } else {
                    // 如果父级记录不存在，设置为顶级
//                    contacts.setParentId(0);
//                    contacts.setCompleteFolder("/");
                    throw new CrmebException("移动到的分组不存在");
                }
            } else {
                // 如果parentId为空或为0，设置为顶级
                contacts.setParentId(0);
                contacts.setCompleteFolder("/");
            }
            
            // 保存到数据库
            return contactsDao.insert(contacts) > 0;
            
        } catch (Exception e) {
            // 记录异常日志
            e.printStackTrace();
            return false;
        }
    }

    //新建通讯录分组
    @Override
    public boolean addGroupContact(Integer parentId, String name, Integer userId, Integer merId) {
        try {
            // 创建新的Contacts对象
            Contacts contacts = new Contacts();
            
            // 设置基本信息
            contacts.setName(name);
            contacts.setUserId(userId);
            contacts.setMerId(merId);
            contacts.setIsFolder(1); // is_folder = 1，表示是文件夹
            contacts.setIsDel(0); // is_del = 0
            contacts.setCreateTime(new Date());
            contacts.setUpdateTime(new Date());
            
            // 处理parentId和complete_folder
            if (parentId != null && parentId > 0) {
                // 如果parentId不为空，获取父级记录的complete_folder
                Contacts parentContact = contactsDao.selectById(parentId);
                if (parentContact != null) {
                    contacts.setParentId(parentId);
                    // 拼接complete_folder：父级的complete_folder + parent_id/
                    String parentCompleteFolder = parentContact.getCompleteFolder();
                    if (parentCompleteFolder != null && !parentCompleteFolder.isEmpty()) {
                        contacts.setCompleteFolder(parentCompleteFolder + parentId + "/");
                    } else {
                        contacts.setCompleteFolder(parentId + "/");
                    }
                } else {
                    // 如果父级记录不存在，抛出异常
                    throw new CrmebException("分组不存在");
                }
            } else {
                // 如果parentId为空或为0，设置为顶级
                contacts.setParentId(0);
                contacts.setCompleteFolder("/");
            }
            
            // 保存到数据库
            return contactsDao.insert(contacts) > 0;
            
        } catch (Exception e) {
            // 记录异常日志
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean moveGroupContact(Integer parentId, Integer id, Integer userId) {
        try {
            // 参数验证
            if (id == null) {
                throw new CrmebException("请选择要移动的通讯录或分组");
            }

            // 获取要移动的记录
            Contacts moveContact = contactsDao.selectById(id);
            if (moveContact == null) {
                throw new CrmebException("要移动的记录不存在");
            }

            // 检查权限：比较user_id和userId
            if (!moveContact.getUserId().equals(userId)) {
                throw new CrmebException("您无权进行该操作");
            }

            // 处理parentId，默认为0
            Integer targetParentId = parentId == null ? 0 : parentId;

            // 获取旧的完整路径
            String completeFolderOld = moveContact.getCompleteFolder();
            if (completeFolderOld == null) {
                completeFolderOld = "";
            }
            String oldPath = completeFolderOld + id + "/";

            // 计算新的完整路径
            String completeFolder = "/";
            if (targetParentId != 0) {
                Contacts parent = contactsDao.selectById(targetParentId);
                if (parent == null) {
                    throw new CrmebException("目标分组不存在");
                }

                // 检查目标父级权限
                if (!parent.getUserId().equals(userId)) {
                    throw new CrmebException("您无权进行该操作");
                }

                // 检查目标父级是否为文件夹
                if (parent.getIsFolder() == 0) {
                    throw new CrmebException("请对文件夹进行操作");
                }

                completeFolder = parent.getCompleteFolder() + parent.getId() + "/";
            }

            // 如果是文件夹类型，更新所有子项的complete_folder
            if (moveContact.getIsFolder() == 1) {
                // 只有原记录是文件夹类型，才更新所有子文件夹和文件的complete_folder
                UpdateWrapper<Contacts> updateWrapper = new UpdateWrapper<>();
                updateWrapper.likeRight("complete_folder", oldPath);
                updateWrapper.setSql("complete_folder = CONCAT('" + completeFolder + id + "/', SUBSTRING(complete_folder, " + (oldPath.length() + 1) + "))");
                contactsDao.update(null, updateWrapper);
            }

            // 同时更新当前记录的parentId和complete_folder
            moveContact.setParentId(targetParentId);
            moveContact.setCompleteFolder(completeFolder);
            moveContact.setUpdateTime(new Date());
            contactsDao.updateById(moveContact);

            return true;
            
        } catch (Exception e) {
            // 记录异常日志
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 批量删除素材
     * @param ids
     * @return
     */
    @Override
    public boolean batchDelContact(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }

        for (Integer id : ids) {
            try {
                delContact(id);
            } catch (Exception e) {
                // 记录错误但继续处理其他ID
                System.err.println("删除通讯录ID " + id + " 失败: " + e.getMessage());
            }
        }

        return true;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    private void delContact(Integer id) {
        Contacts contacts = contactsDao.selectById(id);

        if (contacts == null) throw new CrmebException("通讯录已经被删除或者不存在");
        // 判断是否为文件夹
        if (contacts.getIsFolder() != null && contacts.getIsFolder() == 1) {
            // 文件夹，删除所有子项
            String delFolderId = contacts.getCompleteFolder() + id + "/";
            UpdateWrapper<Contacts> updateWrapper = new UpdateWrapper<>();
            updateWrapper.likeRight("complete_folder", delFolderId);

            updateWrapper.set("is_del", 1);
            contactsDao.update(null, updateWrapper);
        }
        // 删除自身
        contacts.setIsDel(1);
        contacts.setUpdateTime(new Date());
        contactsDao.deleteById(contacts);
    }
} 